// components/CartCpn/CartCpn.js
import { get, post } from "../../utils/request";
import Dialog from "../../miniprogram_npm/@vant/weapp/dialog/dialog";
import Toast from "../../miniprogram_npm/@vant/weapp/toast/toast";

Component({
  /**
   * 组件的属性列表
   */
  properties: {},

  data: {
    result: [], //已选中的购物车商品数组
    cartList: [], //购物车商品数组
    checked: true, //全选按钮状态
    totalPrice: 0, //总价
    show: false, //sku显示状态
    currentGoodsInfo: null, //当前商品信息
    currentSku: [], //当前规格数组
    number: 1, //当前sku数量
    cartId: 0, //当前购物车id
  },
  observers: {
    //watch监听
    result(result) {
      //监听已选中的数组
      // console.log(result);
      // 如果已选中数组的长度等于购物车列表的长度则让全选按钮选中(result不能为0)
      if (result.length) {
        if (result.length === this.data.cartList.length) {
          this.setData({
            checked: true,
          });
        } else {
          //否则为未全部选中，进行取反
          this.setData({
            checked: false,
          });
        }
      }
    },
  },
  methods: {
    //选中改变时
    checkChange(event) {
      this.setData({
        //改变选中
        result: event.detail,
      });
      const ress = event.detail; //保存已选中的数组
      // 做是否全选判断
      if (this.data.result.length === this.data.cartList.length) {
        this.setData({
          checked: true,
        });
      } else {
        this.setData({
          checked: false,
        });
      }

      //循环查询商品数组
      const arr = [];
      for (let i of this.data.cartList) {
        if (!ress.includes(i.id.toString())) {
          //如果ress里面不包含购物车数组里面的某项
          const info = {
            //保存信息
            productIds: [i.productId],
            isChecked: false,
          };
          post({
            //取消选中
            url: "/cart/checked",
            data: info,
          });
        } else {
          //否取反
          arr.push(i);
          const info = {
            productIds: [i.productId],
            isChecked: true,
          };
          post({
            url: "/cart/checked",
            data: info,
          });
        }
      }
      // console.log(arr);
      let total = 0;
      for (let i of arr) {
        total += i.price;
      }
      this.setData({
        totalPrice: total,
      });
    },
    //全选按钮发生改变时
    changeAllChecked(event) {
      this.setData({
        //更改选中状态
        checked: event.detail,
      });
      let totalPrice = 0;
      if (this.data.checked) {
        //如果更改后是选中状态
        const result = [];
        for (let i of this.data.cartList) {
          //循环选中所有商品
          result.push(i.id.toString()); //把所有商品购物车id放进数组
          totalPrice += i.price; //计算总价
        }
        this.setData({
          result,
          totalPrice,
        });
      } else {
        this.setData({
          //否则清空所有选中
          result: [],
          totalPrice: 0,
        });
      }
    },
    //选择规格
    selectSku({
      currentTarget: {
        dataset: { item },
      },
    }) {
      // console.log(item);
      this.setData({
        show: true,
        cartId: item.id,
        number: item.number,
      });
      const info = {
        id: item.goodsId,
      };
      get({
        url: "goods/detail",
        data: info,
      }).then(({ data }) => {
        this.setData({
          currentGoodsInfo: data.data.info,
          currentSku: data.data.productList,
        });
      });
    },
    //选择数量
    changeNumber(e) {
      this.setData({
        number: e.detail,
      });
    },
    //关闭sku
    onClose() {
      this.setData({
        show: false,
        number: 1,
      });
    },
    //确认规格
    confirmSku(e) {
      const info = {
        productId: this.data.currentSku[0].id,
        goodsId: this.data.currentGoodsInfo.id,
        number: this.data.number,
        id: this.data.cartId,
      };
      // console.log(info);
      post({
        url: "/cart/update",
        data: info,
      }).then((res) => {
        if (res.data.errno === 0) {
          this.setData({
            show: false,
          });
          this.computedTotalPrice();
          this.getCartList()
        }
      });
    },
    // 计算总价格
    computedTotalPrice() {
      let total = 0;
      for (let i of this.data.cartList) {
        if (i.checked) {
          total += i.number * i.price;
        }
      }
      this.setData({
        totalPrice: total,
      });
    },
    //删除购物车子项
    del({
      //触发时间
      currentTarget: {
        dataset: { index }, //解构出index索引
      },
    }) {
      Dialog.confirm({
        //确定是否删除
        title: "确定删除吗？",
        context: this,
        selector: "#van-dialog",
      })
        .then(() => {
          //获取当前索引对应的商品的规格id
          const productIds = [this.data.cartList[index].productId];
          post({
            //发送请求
            url: "/cart/delete",
            data: {
              productIds,
            },
          }).then((res) => {
            //如果返回状态码是0代表删除成功
            if (res.data.errno === 0) {
              Toast.success({
                message: "删除成功",
                context: this,
                selector: "#van-toast",
              });
              // 在当前购物车数组删除对应索引的商品项
              this.data.cartList.splice(index, 1);
              this.data.result.splice(index, 1);
              //重新设置购物车商品数组
              this.setData({
                cartList: this.data.cartList,
                result: this.data.result,
              });
              this.computedTotalPrice(); //重新计算总价格
            }
          });
        })
        .catch(() => {
          // on cancel
        });
    },
    //提交订单
    onClickButton() {
      wx.navigateTo({
        url: "../OrderCreate/OrderCreate",
      });
    },
    getCartList() {
      get({
        url: "/cart/index",
      }).then(({ data }) => {
        if (data.errno === 0) {
          //获取数据后
          const arr = []; //保存进result进行选中操作的数组
          const priceArr = [];
          // console.log(data.data.cartList);
          for (let i of data.data.cartList) {
            //遍历根据已经选中的cart商品来渲染勾选状态
            if (i.checked) {
              arr.push(i.id.toString());
              priceArr.push(i);
            }
          }
          this.setData({
            //保存数据
            cartList: data.data.cartList,
            result: arr,
          });

          this.computedTotalPrice();
        }
      });
    }
  },
  pageLifetimes: {
    show() {
      //购物车页面显示时
      const userInfo = wx.getStorageSync("userInfo"); //获取用户缓存信息
      console.log(userInfo);
      if (userInfo) {
        console.log('有信息');
        //如果有缓存信息就发送请求
        this.getCartList()
      }
    },
    hide() {
      //购物车页面隐藏时
      this.setData({
        cartList: [],
        result: [],
      });
    },
  },
});
